﻿using iMES.Core.Enums;
using iMES.Core.Extensions;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Custom.Services;
using iMES.Entity.DomainModels;
using iMES.Inventory.IRepositories;
using iMES.Inventory.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iMES.Inventory.Services
{
    public partial class View_OutboundServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IView_OutboundReprository _view_OutboundReprository;
        private readonly IBase_NumberRuleRepository _numberRuleRepository;

        [ActivatorUtilitiesConstructor]
        public View_OutboundServices(
            IView_OutboundReprository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBase_NumberRuleRepository numberRuleRepository)
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _view_OutboundReprository = dbRepository;
            _numberRuleRepository = numberRuleRepository;
        }

        WebResponseContent WebResponseContent = new WebResponseContent();

        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            AddOnExecuting = ( Inventory_Outbound Outbound,object list) =>
            {
                if (string.IsNullOrWhiteSpace(Outbound.OutWareHouseBillCode))
                    Outbound.OutWareHouseBillCode = GetOutWareHouseBillCode();
                //如果返回false,后面代码不会再执行
                if (repository.Exists(x => x.OutWareHouseBillCode == Outbound.OutWareHouseBillCode))
                {
                    return WebResponseContent.Error("出库单编号已存在");
                }
                return WebResponseContent.OK();
            };
            return base.Add(saveDataModel);
        }
        public override object GetDetailPage(PageDataOptions pageData)
        {
            var query = View_OutboundDetailsReprository.Instance.IQueryablePage<Inventory_OutboundDetails>(
                 pageData.Page,
                 pageData.Rows,
                 out int count,
                 x => x.OutWareHouseBill_Id == pageData.Value.GetInt(),
                  orderBy: x => new Dictionary<object, QueryOrderBy>() { { x.CreateDate, QueryOrderBy.Desc } }
                );
            PageGridData<Inventory_OutboundDetails> detailGrid = new PageGridData<Inventory_OutboundDetails>();
            detailGrid.rows = query.ToList();
            detailGrid.total = count;
            //获取当前库存数量
            List<Base_Product> storeList = Base_ProductService.GetStoreNumber();
            for (int i = 0; i < detailGrid.rows.Count; i++)
            {
                if (storeList.Exists(x => x.Product_Id == detailGrid.rows[i].Product_Id))
                {
                    detailGrid.rows[i].InventoryQty = storeList.Find(x => x.Product_Id == detailGrid.rows[i].Product_Id).InventoryQty;
                }
                else
                {
                    detailGrid.rows[i].InventoryQty = 0;
                }
            }
            return detailGrid;
        }
        /// <summary>
        /// 自动生成工序编号
        /// </summary>
        /// <returns></returns>
        public string GetOutWareHouseBillCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.OutWareHouseBillCode.Length > 8)
                .OrderByDescending(x => x.OutWareHouseBillCode)
                .Select(s => s.OutWareHouseBillCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "OutStoreForm")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
    }
}
